package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.LoginUser;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

//    public User handleLogin(Account account) {
//        User dbuser = userMapper.selectByRoleAndUserName(account.getRole(), account.getUsername());
//        if (ObjectUtil.isNull(dbuser)) {
//            throw new CustomException("用户不存在");
//        }
//        if (!account.getPassword().equals(dbuser.getPassword())) {
//            throw new CustomException("账号或密码错误");
//        }
//        return dbuser;
//    }

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.selectByUserName(userName);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        // TODO 根据用户查询权限信息 添加到LoginUser中
        //封装成UserDetails对象返回
        return new LoginUser(user);
    }
}
